package com.netkiller.mailmonitor.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.model.OAuthRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netkiller.mailmonitor.entity.AppUser;
import com.netkiller.mailmonitor.vo.AppProperties;

import at.tomtasche.contextio.ContextIO;

@Service
public class ContextIOService {

	@Autowired
	AppProperties appProperties;

	@Autowired
	AppUserService appUserService;

	/**
	 * Sync user mail box with context io
	 * @param contextIoId
	 * @return
	 */
	public String syncUserMailBox(String contextIoId) {
		ContextIO dokdok = new ContextIO(appProperties.getContextioKey(),
				appProperties.getContextioSecret());
		return dokdok.syncMailBox(contextIoId);
	}
	public String fetchMailsByUser(String userId, Date from, Date to) {
		AppUser appUser = appUserService.getUser(userId);
		return fetchMailsByUser(appUser,from,to);
	}
	/**
	 * fetch mail box for user
	 * @param appUser
	 * @param from
	 * @param to
	 * @return
	 */
	public String fetchMailsByUser(AppUser appUser, Date from, Date to) {
		String result = "[";
		String userId = appUser.getEmail();
		if (appUser != null && !StringUtils.isBlank(appUser.getContextioId())) {
			ContextIO dokdok = new ContextIO(appProperties.getContextioKey(),
					appProperties.getContextioSecret());
			Map<String, String> params = new HashMap<String, String>();
			int offset = 0;
			int limit = 600;
			String fromTime = "0";
			if (from != null) {
				fromTime = (from.getTime() / 1000) + "";
				params.put("date_after", fromTime);
			}

			if (to != null) {
				String toTime = (to.getTime() / 1000) + "";
				params.put("date_before", toTime);
			}
			// params.put("since", fromTime);
			params.put("limit", limit + "");
			String fetchedResult = "";
			long taskStart = new Date().getTime();
			long timeRunning = 0l;
			while (!fetchedResult.trim().equals("[]") && timeRunning < 480) {
				timeRunning = (new Date().getTime() - taskStart) / 1000;
				System.out.println("time running for " + userId + ": "
						+ timeRunning);
				params.put("offset", offset + "");
				fetchedResult = dokdok.fetchMails(appUser, params).trim();
				if(fetchedResult.equalsIgnoreCase("error") && result.equals("[")){
					result += fetchedResult +"$";
					break;
				}
				result += fetchedResult
						.substring(1, fetchedResult.length() - 1) + ",";
				offset += limit;
				// System.out.println("fetched============== " +fetchedResult );
				if (timeRunning >= 480) {
					System.out.println("Stop fetching for " + userId);
				}
			}
			result = result.substring(0, result.length() - 1);
		}
		result += "]";
		return result;
	}
	
	

	/**
	 * Add user to application
	 * @param appUser
	 * @return
	 */
	public String addSource(AppUser appUser) {
			ContextIO dokdok = new ContextIO(appProperties.getContextioKey(),
					appProperties.getContextioSecret());
			
			
			Map<String, String> sourceParams = new HashMap<String, String>();	
			sourceParams.put("email", appUser.getEmail());
			sourceParams.put("server", "imap.gmail.com");
			sourceParams.put("username", appUser.getEmail());		
			sourceParams.put("use_ssl", "1");
			sourceParams.put("port", "993");
			sourceParams.put("type", "IMAP");
			
			/*sourceParams.put("service_level", "BASIC");
			sourceParams.put("sync_period", "6h");*/
			sourceParams.put("sync_all_folders", "1");
			
			sourceParams.put("provider_token", appUser.getAccessTokenKey());
			sourceParams.put("provider_token_secret", appUser.getAccessTokenSecret());
			sourceParams.put("provider_consumer_key", appProperties.getConsumerKey());
			
			String response = null;
			for (int i = 0; i < 5; i++) {
				try {
					response = dokdok.addSource(sourceParams, appUser);
					break;
				} catch (Exception e) {
					System.out.println("retry for " + appUser.getEmail());
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
			System.out.println(response);
			return response;

	}

}
